import axios from 'axios'
import { handleGetToken, getAppInfo } from '@/utils/bridge'
import { API_MK_URL } from './config'

const networkError = {
  zh: '网络异常',
  ar: 'الشبكة خطا',
  en: 'Network Error',
  es: 'Internet desconectable',
}

const { lz } = window

// 创建一个带默认配置 axios 对象，就是一个axios，可以像 axios 一样使用
const instance = axios.create({
  // baseURL: MOCK_URL,
  baseURL: API_MK_URL,
  timeout: 30000,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
  needToken: true, // 是否需要 token 令牌
})

// 配置项
let APP_INFO = null
let TOKEN
let manual_token = '6327d7fbf26d493b8af20ffbb0a0fed7'
let lang = ''
// let activityId = 4

// 验证响应数据是否成功获取
const handleRcode = async (response) => {
  const { data } = response
  // 判断 rCode 状态，401 token验证过期
  if (data.rCode === 0 || data.rcode === 0) {
    return Promise.resolve(data.data || {})
  } else if (data.rCode === 401 && !response.config.isRetry) {
    // token 过期，重新获取 token
    TOKEN = await handleGetToken(manual_token)
    response.config.isRetry = true
    return instance(response.config) // token 过期更新，重新发送上一次请求
  } else {
    return Promise.reject(data)
  }
}

// 请求处理，请求拦截器
instance.interceptors.request.use(
  async (request) => {
    // 判断是否需要 token 令牌
    if (request.needToken) {
      TOKEN = TOKEN || (await handleGetToken(manual_token))
      request.headers.sessionId = TOKEN
    }

    // 整合 appInfo 数据
    if (!APP_INFO) {
      APP_INFO = await getAppInfo()
    }

    request.headers = Object.assign({}, request.headers, APP_INFO)

    return request
  },
  async (err) => {
    if (!lang) {
      let info = (lz && (await lz.getAppInfo())) || {}
      lang = info.lang
    }
    lz && lz.showPrompt({ type: 0, msg: networkError[lang] })
    return Promise.reject(err)
  },
)

// 响应处理，响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return handleRcode(response)
    }
    return Promise.reject(response)
  },
  async (err) => {
    if (!lang) {
      let info = (lz && (await lz.getAppInfo())) || {}
      lang = info.lang
    }

    lz && lz.showPrompt({ type: 0, msg: networkError[lang] })
    return Promise.reject(err)
  },
)

export default instance
